#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <string>
#include <cstdlib>
#include <memory>
#include <functional>
#include <unistd.h>
#include "InitAddr.hpp"
#include "Common.hpp"

namespace SocketModule
{
    const static uint16_t default_port = 8080;
    const static int default_backlog = 10;

    class Socket
    {
    public:
        virtual ~Socket() {}

        virtual void SocketOrDie() = 0;

        virtual void BindOrDie(uint16_t) = 0;

        virtual void ListenOrDie(int) = 0;

        virtual std::unique_ptr<Socket> Accept(InitAddr &) = 0;

        virtual void Close() = 0;

        virtual int Recv(std::string* out) = 0;

        virtual int Send(const std::string out) = 0;

    public:
        void BuildListenSocket()
        {
            // 模板方法模式：对上面的纯虚方法做组合，但是子类必须完成重写
            SocketOrDie();
            BindOrDie(default_port);
            ListenOrDie(default_backlog);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(){}
        
        TcpSocket(int fd)
            : _isrunning(true)
            , _sockfd(fd)
        {
        }

        virtual ~TcpSocket() override
        {
        }

        virtual void SocketOrDie() override
        {
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                std::cout << "socket fail" << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "socket success" << std::endl;
        }

        virtual void BindOrDie(uint16_t port = default_port) override
        {
            InitAddr addr(port); //设置sockaddr_in中的相关字段信息的封装结构体
            int n = bind(_sockfd, addr.NetAddrPtr(), addr.NetAddrLen());
            if (n < 0)
            {
                std::cout << "bind fail" << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind success" << std::endl;
        }

        virtual void ListenOrDie(int backlog = default_backlog) override
        {
            //进行监听
            int n = listen(_sockfd, backlog);
            if (n < 0)
            {
                std::cout << "listen fail" << std::endl;
                exit(LISTEN_ERR);
            }
            std::cout << "listen success" << std::endl;
        }

        virtual std::unique_ptr<Socket> Accept(InitAddr &client) override
        {
            //类似于前面的BindOrDie，将listen监听得到的套接字与相应的结构体进行绑定以急性相关处理
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = accept(_sockfd, CONV(peer), &len);
            client.SetAddr(peer);
            return std::make_unique<TcpSocket>(fd);
        }

        virtual int Recv(std::string* out) override
        {
            char buffer[4096*4]; //如果这里想要读取图片的话，最好把缓冲区设的大一点，否则图片可能会出现读取失败
            int n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }
            return n;
        }

        virtual int Send(const std::string out) override
        {
            //recv and send的使用方式类似于read和write但是区别在与他们需要在最后加上模式
            return ::send(_sockfd, out.c_str(), out.size(), 0);
        }

        void Close()
        {
            if(!_isrunning)
                close(_sockfd);
        }

    private:
        int _sockfd;
        bool _isrunning;
    };
}